package com.cx.update;


import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Environment;
import android.text.TextUtils;

import java.io.File;

public class UpdateUtils {
    public static final String DEFAULT_FOLDER = ".sunUpdate";
    private String oldVersion = "";
    private String mVersionAddress = "";
    private UpdateInfo updateInfo = null;
    public  static  UpdateInfo MaxVerInfo = null;
    private String fileSavePath = "";
    private String MD5 = "";
    public static final int DOWNLOAD_SUCCESS = 0;
    public static final int DOWNLOAD_CONNECT_ERROR = -1;
    public static final int DOWNLOAD_TIME_OUT = -2;
    public static final int DOWNLOAD_NO_INPUTSTREAM = -3;
    public static final int DOWNLOAD_ERROR_FILE = -4;
    public static final int DOWNLOAD_UNKNOWN = -5;
    public static final int UPDATE_FAILED = -1;
    public static final int UPDATE_NEED = 0;
    public static final int UPDATE_EMPTY_ADDRESS = -2;
    public static final int UPDATE_NOT_NEED = -3;
    public DownloadPrecentListener mListener = null;

    private Context ctx=null;
    private String packageName=null;
    private String version;
    private String rsaMd5;

    public UpdateUtils() {
    }

    public void init(Context ctx)
    {
        this.ctx = ctx;
        packageName = ctx.getPackageName();
        version = getVersionCode();
        rsaMd5 = getSingMD5();
    }
    /**
     * 鑾峰彇鑷韩apk绛惧悕md5鍊笺��
     * @return
     */
    public String getSingMD5() {
        String ret=null;
        try {
            PackageInfo packageInfo = ctx.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
            Signature signatures = packageInfo.signatures[0];
            ret = MD5Util.getMD5String(signatures.toByteArray());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return ret;
    }

    /**
     * 鑾峰彇鑷韩鐗堟湰
     * @return
     */
    public String getVersionCode() {
        String version = "1.0.0";
        PackageInfo packInfo = null;
        try {
            packInfo = ctx.getPackageManager().getPackageInfo(packageName, 0);
            version = packInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }
    public int setUpdateAddress(String address) {
        if(VersionParser.isEmptyText(address)) {
            return -2;
        } else {
            this.oldVersion = version;
//            this.mVersionAddress = address + version;
            this.mVersionAddress = address+packageName.replaceAll("\\.","_")+".json?r="+System.currentTimeMillis();
          System.out.println(rsaMd5+" rsaMd5 "+oldVersion);
            return VersionParser.updateUrl(this.mVersionAddress, this.oldVersion, this,rsaMd5);
        }
    }

    public String getMD5() {
        return this.MD5;
    }

    public void setMD5(String mD5) {
        this.MD5 = mD5;
    }

    public String getUpdateVersion() {
        return this.updateInfo != null?this.updateInfo.getTagVersion():"";
    }

    public String[] getMessage() {
        return this.updateInfo != null?this.updateInfo.getMessage():null;
    }

    public int startDownload(String saveFolder, String fileName) {
        if(!Environment.getExternalStorageState().equals("mounted")) {
            return -5;
        } else if(this.updateInfo == null) {
            return -5;
        } else {
            File file = new File(saveFolder);
            if(!file.exists()) {
                file.mkdir();
            }

            if(VersionParser.isEmptyText(saveFolder)) {
                saveFolder = ".sunUpdate";
            }

            File apkFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + saveFolder, fileName);
            HttpUtil mHttpUtil = new HttpUtil();
            int resultCode = mHttpUtil.downFile(this.updateInfo.getUrl(), saveFolder, fileName, this.mListener);
            if(resultCode == 0) {
                String md5 = MD5Util.getFileMD5String(apkFile);
               
                if(md5.equalsIgnoreCase(this.updateInfo.getMd5())) {
                    this.setFileSavePath(apkFile.getAbsolutePath());
                    return 0;
                } else {
                    return -4;
                }
            } else {
                return resultCode;
            }
        }
    }

    public int startDownload(String url, String saveFolder, String fileName, String md5) {
        if(!Environment.getExternalStorageState().equals("mounted")) {
            return -5;
        } else {
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator +saveFolder);
            if(!file.exists()) {
                file.mkdir();
            }

            if(VersionParser.isEmptyText(saveFolder)) {
                saveFolder = ".sunUpdate";
            }

            File apkFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + saveFolder, fileName);
            HttpUtil mHttpUtil = new HttpUtil();
            int resultCode = mHttpUtil.downFile(url, saveFolder, fileName, this.mListener);
            if(resultCode == 0) {
                this.setFileSavePath(apkFile.getAbsolutePath());
                if(!TextUtils.isEmpty(md5)) {
                    String loadmd5 = MD5Util.getFileMD5String(apkFile);
                    System.out.println("apkmd5 "+loadmd5);
                    return md5.equalsIgnoreCase(loadmd5)?0:-4;
                } else {
                    return 0;
                }
            } else {
                return resultCode;
            }
        }
    }

    public String getFileSavePath() {
        return this.fileSavePath;
    }

    public void setFileSavePath(String fileSavePath) {
        this.fileSavePath = fileSavePath;
    }

    public UpdateInfo getUpdateInfo() {
        return this.updateInfo;
    }

    public void setUpdateInfo(UpdateInfo updateInfo) {
        this.updateInfo = updateInfo;
    }

    public void setMaxVersionInfo(UpdateInfo updateInfo)
    {
        MaxVerInfo = updateInfo;
    }

    public void setDownloadPrecentListener(DownloadPrecentListener downloadPrecentListener) {
        this.mListener = downloadPrecentListener;
    }
}
